<?php

namespace App\Http\Controllers;

use Beike\Models\Category;
use Beike\Models\CategoryDescription;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class CategoryController extends Controller
{
    /**
     * Import categories with descriptions
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        try {
            // Define validation rules
            $rules = [
                'categories' => 'required|array',
                'categories.*.descriptions' => 'required|array|min:1',
                'categories.*.descriptions.*.locale' => 'required|string|in:en,zh_cn',
                'categories.*.descriptions.*.name' => 'required|string|max:191',
                'categories.*.descriptions.*.content' => 'nullable|string',
                'categories.*.descriptions.*.meta_title' => 'nullable|string|max:191',
                'categories.*.descriptions.*.meta_description' => 'nullable|string',
                'categories.*.descriptions.*.meta_keywords' => 'nullable|string',
                'categories.*.parent' => 'nullable|string|max:191', // 修改为字符串分类名称
                'categories.*.position' => 'integer|min:0',
                'categories.*.active' => 'boolean',
                'categories.*.images' => 'nullable|array',
                'categories.*.images.*' => 'string',
                'categories.*.sort_order' => 'integer|min:0',
            ];

            $validator = Validator::make($request->all(), $rules);
            if ($validator->fails()) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Validation failed',
                    'errors' => $validator->errors(),
                ], 422);
            }

            // Begin database transaction
            DB::beginTransaction();
            
            $results = [];
            $importedCount = 0;
            $skippedCount = 0;
            $failedCategories = [];

            foreach ($request->categories as $index => $categoryData) {
                try {
                    $categoryId = null;
                    $status = 'failed';
                    $message = '';
                    $resolvedParentId = 0;
                    
                    // 提取英语描述
                    $englishDescription = collect($categoryData['descriptions'])
                        ->firstWhere('locale', 'en');
                    
                    if (!$englishDescription) {
                        throw new \Exception('English description (locale: en) is required');
                    }

                    $englishName = $englishDescription['name'];

                    // 处理父分类：通过parent字符串名称查询parent_id
                    if (!empty($categoryData['parent'])) {
                        $parentId = $this->findCategoryByEnglishName($categoryData['parent']);
                        if (!$parentId) {
                            throw new \Exception("Parent category '{$categoryData['parent']}' not found");
                        }
                        $resolvedParentId = $parentId;
                    }

                    // 只根据英语名称检查分类是否已存在
                    $existingCategory = CategoryDescription::where('name', $englishName)
                        ->where('locale', 'en')
                        ->join('categories', 'category_descriptions.category_id', '=', 'categories.id')
                        ->first();

                    if ($existingCategory) {
                        // 分类已存在（英语名称匹配），返回现有分类ID
                        $categoryId = $existingCategory->category_id;
                        $status = 'skipped';
                        $message = 'Category already exists (English name matched)';
                        $skippedCount++;
                    } else {
                        // 创建新分类，使用解析得到的parent_id
                        $category = Category::create([
                            'parent_id' => $resolvedParentId,
                            'position' => $categoryData['position'] ?? 0,
                            'active' => $categoryData['active'] ?? true,
                            'images' => $categoryData['images'] ?? null,
                            'sort_order' => $categoryData['sort_order'] ?? 0,
                        ]);

                        // 创建所有语言的分类描述
                        foreach ($categoryData['descriptions'] as $description) {
                            CategoryDescription::create([
                                'category_id' => $category->id,
                                'locale' => $description['locale'],
                                'name' => $description['name'],
                                'content' => $description['content'] ?? '',
                                'meta_title' => $description['meta_title'] ?? '',
                                'meta_description' => $description['meta_description'] ?? '',
                                'meta_keywords' => $description['meta_keywords'] ?? '',
                            ]);
                        }

                        $categoryId = $category->id;
                        $status = 'imported';
                        $message = 'Category created successfully';
                        $importedCount++;
                    }

                    // 添加到结果数组
                    $results[] = [
                        'index' => $index,
                        'category_id' => $categoryId,
                        'out_id' => isset($categoryData['out_id'])?$categoryData['out_id']:0,
                        'english_name' => $englishName,
                        'parent' => $categoryData['parent'] ?? null,
                        'resolved_parent_id' => $resolvedParentId,
                        'status' => $status,
                        'message' => $message,
                    ];

                } catch (\Exception $e) {
                    $englishName = $englishDescription['name'] ?? 'Unknown';
                    $failedCategories[] = [
                        'index' => $index,
                        'english_name' => $englishName,
                        'parent' => $categoryData['parent'] ?? null,
                        'error' => $e->getMessage(),
                    ];
                    
                    Log::error('Category import failed: ' . $e->getMessage(), [
                        'index' => $index,
                        'category_data' => $categoryData,
                        'error_line' => $e->getLine()
                    ]);
                }
            }

            // Commit transaction
            DB::commit();

            $response = [
                'status' => 'success',
                'message' => "Import completed",
                'summary' => [
                    'imported' => $importedCount,
                    'skipped' => $skippedCount,
                    'failed' => count($failedCategories),
                ],
                'results' => $results,
                'failed_details' => $failedCategories,
            ];

            return response()->json($response, 201);

        } catch (\Exception $e) {
            // Rollback transaction on error
            DB::rollBack();
            
            Log::error('Categories import failed: ' . $e->getMessage(), [
                'request_data' => $request->all(),
                'error_line' => $e->getLine()
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'Failed to import categories',
                'error' => $e->getMessage(),
                'results' => [],
            ], 500);
        }
    }

    /**
     * 检查英语分类名称是否存在并返回分类ID
     *
     * @param string $englishName
     * @return int|null
     */
    private function findCategoryByEnglishName(string $englishName): ?int
    {
        $categoryDescription = CategoryDescription::where('name', $englishName)
            ->where('locale', 'en')
            ->join('categories', 'category_descriptions.category_id', '=', 'categories.id')
            ->first();
            
        return $categoryDescription ? $categoryDescription->category_id : null;
    }
}